using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;



#if UNITY_EDITOR
using UnityEditor;
//[ExecuteAlways]
#endif
public class SFrameworkGate : MonoBehaviour
{
    public static string rootPath => Application.dataPath + "/only-sframework/";
    public static string appDefinePath => "Assets/only-sframework/Data/Database/";

    public static bool InEditor
    {
        get
        {
#if DEBUG && UNITY_EDITOR
            return true;
#endif
            return false;
        }
    }
    public static bool IsPlaying => Application.isPlaying;

    public static SFrameworkGate instance;
#if DEBUG && UNITY_EDITOR
    [RuntimeInitializeOnLoadMethod]
#else
    [RuntimeInitializeOnLoadMethod]
#endif
    public static void BootGate()
    {
        var gateGo = "SFrameworkGate".GlobalUniqueGameObject();
        var gate = gateGo.UniqueComponent<SFrameworkGate>();
        instance = gate;

        staticInitSequence[0] = () =>
        {
            var Observer = gateGo.UniqueComponent<ObserverSystem>();
            Observer.InitObserverSystem();
        };

        staticInitSequence[2] = () =>
        {
            var llmGate = gateGo.UniqueComponent<VLLMGate>();
            llmGate.Init();
        };

        //staticInitSequence[3] = () =>
        //{
        //    var PWareHouse = gateGo.UniqueComponent<PWarehouse>();
        //    PWareHouse.InitWarehouse();
        //};

        staticInitSequence[4] = () =>
        {
            //这里还得处理异步的加载, 且操作柄在传递中是被屏蔽的,只能靠经验去等待一个时长 , 或者可以把操作柄都收集到栈中按固定时长等待直至全部释放 ,这是比较正确的
            LoadSystem.PreloadAssets();
        };

        //staticInitSequence[5] = () =>
        //{
        //    var VGUIgo = "VGUI".GlobalUniqueGameObject();
        //    var eventsystemgo = "EventSystem".GlobalUniqueGameObject(); //如果是在VR下是否有不同
        //    var VGUI = VGUIgo.UniqueComponent<VGUI>();
        //    0.5f.Delay(VGUI.Init);
        //};

        staticInitSequence[6] = () =>
        {
            var VAudioGo = "VAudio".GlobalUniqueGameObject();
            var VAudio = VAudioGo.UniqueComponent<VAudio>();
            VAudio.Init();
        };

        //升序调用一遍完成初始化 , 可以考虑用特性标注
        staticInitSequence
        .OrderBy(pair => pair.Key)
        .ToList()
        .ForEach(x => x.Value?.Invoke());
    }
    private void OnEnable()
    {
        BootGate();

        // startInitSequence[0] = () =>
        // {
        //     PokeXRManager.Init();
        // };


        startInitSequence
.OrderBy(pair => pair.Key)
.ToList()
.ForEach(x => x.Value?.Invoke());

        Debug.Log("---SGate Init---\n" + logtemp);
        logtemp = "";
    }

    public static Dictionary<int, Action> staticInitSequence = new();
    public Dictionary<int, Action> startInitSequence = new();
    public static string logtemp;
    public static void Log(string log) => logtemp += log + "\n";
}
